# coding=utf-8
import sys
from . import admin
from flask import request, redirect, render_template, jsonify
from app.MySession import MySession
from dbConnection.MysqlConn import Mysql
from app import util
import time

reload(sys)
sys.setdefaultencoding('utf8')


# 权限列表
@admin.route('/admin/power.html')
@util.login_required
def power_list():
    # uid = request.cookies.get('uid')
    # if uid is None or not MySession.reactive(uid):
    #     return redirect('/')
    uid = request.args.get('uid')
    res = get_admin_data(uid)
    # if res is None:
    #     return redirect('/')
    return render_template('admin/setting/power.html', res=res, uid=uid)


# 获取用户权限
@admin.route('/admin/permission_data', methods=['POST'])
@util.login_required
def permission_data():
    uid = request.cookies.get('uid')
    if not MySession.reactive(uid):
        data = {
            'status': 0
        }
        return jsonify(data)
    cur_id = request.values.get('user_id')
    if cur_id == '' or cur_id == 'None':
        data = {
            'status':0
        }
        return jsonify(data)
    sql = "select small FROM news_route_group WHERE action_id = '%s'" % cur_id
    mysql = Mysql()
    res = mysql.getOne(sql, None)
    if res['small'] is None:
        data = {
            'status':0
        }
        mysql.dispose()
        return jsonify(data)
    sql2 = "select route_info FROM news_route_url WHERE route_id in(%s)" % res['small']
    con = mysql.getAll(sql2, None)
    mysql.dispose()
    if con is None:
        data = {
            'status':0
        }
        mysql.dispose()
        return jsonify(data)
    data = {
        'status':'success',
        'arr':con
    }
    return jsonify(data)


# 更新用户权限
@admin.route('/admin/update_per', methods=['POST'])
@util.login_required
def update_per():
    uid = request.cookies.get('uid')
    if not MySession.reactive(uid):
        data = {
            'status': 0
        }
        return jsonify(data)
    arr = request.values.get('arr')
    cur_id = request.values.get('cur_id')
    if arr == '':
        sql = "update news_route_group SET small = null WHERE action_id = '%s'" % cur_id
        mysql = Mysql()
        res = mysql.update(sql, None)
        mysql.dispose()
        if res >= 0:
            data = {
                'status':1
            }
        else:
            data = {
                'status':0
            }
        return jsonify(data)
    id_list = get_url_id(arr[:-1])
    if id_list == '':
        sql = "update news_route_group SET small = null WHERE action_id = '%s'" % cur_id
        mysql = Mysql()
        res = mysql.update(sql, None)
        mysql.dispose()
        if res >= 0:
            data = {
                'status':1
            }
        else:
            data = {
                'status':0
            }
        return jsonify(data)
    else:
        sql = "update news_route_group SET small = '%s' WHERE action_id = '%s'" % (id_list, cur_id)
        mysql = Mysql()
        res = mysql.update(sql, None)
        mysql.dispose()
        if res >= 0:
            data = {
                'status':1
            }
        else:
            data = {
                'status':0
            }
        return jsonify(data)


# 添加路由
@admin.route('/admin/add_link_list', methods=['POST'])
@util.login_required
def add_link_list():
    uid = request.cookies.get('uid')
    if not MySession.reactive(uid):
        data = {
            'status': 0
        }
        return jsonify(data)
    link_name = request.values.get('link_name').strip()
    link_address = request.values.get('link_address').strip()
    res = get_link_name(link_name)
    if res is not None:
        data = {
            'status':2
        }
        return jsonify(data)
    con = insert_link(link_name, link_address)
    if con >= 0:
        data = {
            'status':1
        }
    else:
        data = {
            'status':0
        }
    return jsonify(data)


# 获取登陆用户的权限
@admin.route('/admin/jurisdiction', methods=['GET', 'POST'])
@util.login_required
def jurisdiction():
    user = request.cookies.get('user')
    sql = "select u.small FROM admin AS a LEFT JOIN news_route_group AS u ON a.id = u.action_id WHERE a.username = '%s'" % user
    mysql = Mysql()
    res = mysql.getOne(sql, None)
    mysql.dispose()
    if res is None or res['small'] is None:
        data = {
            'status':'error'
        }
        return jsonify(data)
    if res['small'] == 'all':
        data = {
            'status':'all'
        }
        return jsonify(data)
    sql = "select route_url, route_info FROM news_route_url WHERE route_id in(%s)" % res['small']
    mysql = Mysql()
    con = mysql.getAll(sql, None)
    mysql.dispose()
    if con is None:
        data = {
            'status':'error'
        }
    else:
        data = {
            'status':'success',
            'arr':con
        }
    return jsonify(data)


# 获取管理员的信息
def get_admin_data(uid):
    sql = "select a.*, g.large, g.small FROM admin AS a LEFT JOIN news_route_group AS g ON g.action_id = a.id WHERE a.id = '%s'" % uid
    mysql = Mysql()
    res = mysql.getOne(sql, None)
    mysql.dispose()
    return res


# 查询路由是否已存在
def get_link_name(name):
    sql = "select * FROM news_route_url WHERE route_info = '%s'" % name
    mysql = Mysql()
    res = mysql.getOne(sql, None)
    mysql.dispose()
    return res


# 新增路由
def insert_link(name, url):
    sql = "insert INTO news_route_url(route_url, route_info) VALUES ('%s', '%s')" % (url, name)
    mysql = Mysql()
    res = mysql.insertOne(sql, None)
    mysql.dispose()
    return res


# 返回路由对应的ID
def get_url_id(name):
    try:
        str_id = ''
        name_list = name.split(',')
        mysql = Mysql()
        if len(name_list) < 1:
            return str_id
        for d in name_list:
            sql = "select route_id FROM news_route_url WHERE route_info = '%s'" % d
            res = mysql.getOne(sql, None)
            if res is not None:
                str_id += str(res['route_id']) + ','
        mysql.dispose()
        if str_id != '':
            str_id = str_id[:-1]
        return str_id
    except Exception as e:
        print e
        mysql.dispose()
        return ''